from . import db
from datetime import datetime

class Area(db.Model):
    __tablename__ = 'areas'
    
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), unique=True, nullable=False)  # 区域名称
    leader_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=True)  # 组长ID
    description = db.Column(db.Text, nullable=True)  # 区域描述
    is_active = db.Column(db.Boolean, default=True)  # 是否启用
    
    # 时间戳
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    
    # 关联关系
    leader = db.relationship('User', back_populates='led_areas', foreign_keys=[leader_id])
    members = db.relationship('User', back_populates='area', foreign_keys='User.area_id')
    
    def get_members(self):
        """获取区域成员列表"""
        return self.members
    
    def get_member_count(self):
        """获取区域成员数量"""
        return len(self.members)
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'name': self.name,
            'leader_id': self.leader_id,
            'leader_name': self.leader.name if self.leader else None,
            'leader_username': self.leader.username if self.leader else None,
            'description': self.description,
            'is_active': self.is_active,
            'member_count': self.get_member_count(),
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None
        }
    
    def to_dict_with_members(self):
        """转换为字典（包含成员列表）"""
        result = self.to_dict()
        result['members'] = [{
            'id': member.id,
            'name': member.name,
            'username': member.username,
            'employee_id': member.employee_id,
            'position': member.position,
            'phone': member.phone
        } for member in self.get_members()]
        return result
    
    def __repr__(self):
        return f'<Area {self.name}>'